package com.framework.simplemvc.config;

import cn.dev33.satoken.interceptor.SaAnnotationInterceptor;
import cn.dev33.satoken.interceptor.SaRouteInterceptor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.io.File;
import java.io.FileNotFoundException;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.TimeZone;

@Configuration
@Slf4j
public class WebMvcConfig extends WebMvcConfigurationSupport {


    @Bean
    public StringHttpMessageConverter stringHttpMessageConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
        return converter;
    }

    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
        return converter;
    }

    /**
     * 拦截器 token解析保存用户信息到私有线程
     */
    @Bean
    public UserAuthRestInterceptor userAuthRestInterceptor() {
        return new UserAuthRestInterceptor();
    }

    //路由白名单
    String[] excludePatterns = new String[]{
            "/**/public/**",
            "/static/**",
            "/doc.html",
            "/swagger-resources/**",
            "/swagger/**",
            "/**/v2/api-docs",
            "/webjars/springfox-swagger-ui/**",
            "/**/v2/api-docs",
            "/**/*.woff2",
            "/**/*.js",
            "/**/*.css",
            "/**/*.jpg",
            "/**/*.png",
            "/**/*.ico"
    };

    /**
     * 登陆过滤 保存当前用户信息到 threadload
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SaRouteInterceptor()).addPathPatterns("/**").excludePathPatterns(excludePatterns).order(1);
        //注解式鉴权功能
        registry.addInterceptor(new SaAnnotationInterceptor()).addPathPatterns("/**");

        //token信息保存为 ThreadLocalUtils  用户实体
        registry.addInterceptor(userAuthRestInterceptor())
//                .addPathPatterns("/api/**", "/auth/**")
                .addPathPatterns("/**")
                .excludePathPatterns(excludePatterns)
                .order(5);
        super.addInterceptors(registry);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
//        try {
//            String path = getProPath();
//            String staticPath = "file:" + path + File.separator + "static" + File.separator;
//            String webPath = "file:" + path + File.separator + "web" + File.separator;
//            registry.addResourceHandler("/**", "/static/**").addResourceLocations(staticPath, webPath);
//            log.info("staticPath：" + staticPath);
//        } catch (FileNotFoundException e) {
//        }
//        //registry.addResourceHandler("/**", "/static/**").addResourceLocations("classpath:/static/");
//        /** 文件传路径 */
//        log.info("proConfig.getUploadPath() + File.separator", proConfig.getUploadPath() + File.separator);
//        registry.addResourceHandler("/profile/**").addResourceLocations("file:" + proConfig.getUploadPath() + File.separator);

        //swagger
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    public String getProPath() throws FileNotFoundException {
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!path.exists()) {
            path = new File("");
        }
        return path.getAbsolutePath();
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE);
        objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        simpleModule.addSerializer(BigInteger.class, ToStringSerializer.instance);
//        simpleModule.addSerializer(IEnum.class, new IEnumSerializer());
        objectMapper.registerModule(simpleModule);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        converters.add(jackson2HttpMessageConverter);
        super.configureMessageConverters(converters);
    }


}
